<script setup>

import {onMounted, ref} from "vue";
import {Refresh, Search} from "@element-plus/icons-vue";
import axios from "axios";
import {ElMessage} from "element-plus";

// 分页信息
let pageNum = ref(1)
let pageSize = ref(3)
let total = ref(10)

// 搜索条件
let courseName = ref()
let consultantName = ref()
let courseType = ref()

//判断添加和修改弹出框
let str1 = ref("")
let str2 = ref("添加新课程")
let str3 = ref("")
let str4 = ref("确定删除该条数据吗?")

const formLabelWidth = '140px'
let dialogFormVisibleAdd = ref(false)
let dialogFormVisibleDel = ref(false)


let tableData = ref([])
// 删除的id
let num = ref()
//批量删除的数组
let numArr = ref([])

//视频地址数组
let videoArr = ref([])
//图片地址数组
let imageArr = ref([])
//课程类型数组
let typeArr = ref([])
//咨询师数组
let consultantArr = ref([])

//表单
let form = ref({
  courseId: 0,
  title: "",
  videoUrl: "",
  description: "",
  targetAudience: "",
  learningOutcomes: "",
  subscriptionNotice: "",
  originalPrice: "",
  discount: "",
  imageUrl: "",
  consultant: {
    consultantId: 0,
    realname: null
  },
  validityPeriod: null,
  studyTimes: null,
  coursetype: {
    typeId: 0,
    name: null
  },
  subjectTimes: "",
  lessonNum: 0,
  reviewNum: 0,
  likeNum: 0,
  buyNum: 0,
})

// 分页
const change = (page) => {
  pageNum.value = page;
  console.log(pageNum.value)
  findAll()
}
const prevPage = () => {
  console.log(pageNum.value)
  findAll()
}
const nextPage = () => {
  console.log(pageNum.value)
  findAll()
}

//上传视频和图片

const upload = () => {
  let file1 = new file1("tx1")
  let file2 = new file2("tx2")
  const formData1 = new FormData();
  const formData2 = new FormData();
  formData2.append("file", file2.files[0])
  formData1.append("file", file1.files[0]);
  axios.post("/file", formData1, {
    headers: {"Content-Type": "multipart-form-data"}
  })
}

//添加新课程
const add = () => {
  for (const consultant of consultantArr.value) {
    if (consultant.realname === form.value.consultant.realname) {
      form.value.consultant.consultantId = consultant.consultantId
    }
  }
  for (const type of typeArr.value) {
    if (type.name === form.value.coursetype.name) {
      form.value.coursetype.typeId = type.typeId
    }
  }
  axios.post("/course", form.value)
      .then(res => {
        console.log(res.data)
        findAll()
      })
      .catch(err => console.log(err))
}
const addCourse1 = () => {
  str1.value = "添加新课程"
  form.value = {
    courseId: 0,
    title: "",
    videoUrl: "",
    description: "",
    targetAudience: "",
    learningOutcomes: "",
    subscriptionNotice: "",
    originalPrice: "",
    discount: "",
    imageUrl: "",
    consultant: {
      consultantId: 0,
      realname: null
    },
    validityPeriod: null,
    studyTimes: null,
    coursetype: {
      typeId: 0,
      name: null
    },
    subjectTimes: "",
    lessonNum: 0,
    reviewNum: 0,
    likeNum: 0,
    buyNum: 0,
  }
  dialogFormVisibleAdd.value = true;
  //
  // let  tx1=document.getElementById("tx1");
  // console.log(tx1)


}
const addCourse2 = () => {

  if (form.value.consultant.realname != null && form.value.coursetype.name != null) {
    let file1 = document.getElementById("tx1")
    let file2 = document.getElementById("tx2")
    if (file1.files.length > 0) {
      if (file2.files.length > 0) {
        const formData1 = new FormData();
        const formData2 = new FormData();
        formData2.append("file", file2.files[0]);
        formData1.append("file", file1.files[0]);
        axios.post("/file", formData1, {
          headers: {"Content-Type": "multipart-form-data"}
        })
            .then(res => {
              form.value.videoUrl = res.data
              console.log(res.data)
              axios.post("/file", formData2, {headers: {"Content-Type": "multipart-form-data"}})
                  .then(res => {
                    form.value.imageUrl = res.data
                    console.log(res.data)
                    add()
                  })
                  .catch(err => console.log(err))
            })
            .catch(err => console.log(err))

      } else {
        const formData1 = new FormData();
        formData1.append("file", file1.files[0]);
        axios.post("/file", formData1, {headers: {"Content-Type": "multipart-form-data"}})
            .then(res => {
              form.value.videoUrl = res.data
              add()
            })
            .catch(err => console.log(err))
      }
    } else {
      if (file2.files.length > 0) {
        const formData2 = new FormData();
        formData2.append("file", file2.files[0]);
        axios.post("file", formData2, {headers: {"Content-Type": "multipart-form-data"}})
            .then(res => {
              form.value.imageUrl = res.data
              add()
              console.log(res.data)
            })
            .catch(err => console.log(err))
      } else {
        add()
      }
    }
    dialogFormVisibleAdd.value = false;
  } else {
    ElMessage({
      message: '请选择该课程的咨询师以及课程的类型',
      type: 'error',
      plain: true,
    })
  }

}

//修改课程
const update = () => {
  for (const consultant of consultantArr.value) {
    if (consultant.realname === form.value.consultant.realname) {
      form.value.consultant.consultantId = consultant.consultantId
    }
  }
  for (const type of typeArr.value) {
    if (type.name === form.value.coursetype.name) {
      form.value.coursetype.typeId = type.typeId
    }
  }
  axios.put("/course", form.value)
      .then(res => {
        findAll()
        console.log(res.data)
      })
      .catch(err => console.log(err))
}
const changeCourse1 = (obj) => {
  str1.value = "修改课程"
  form.value = obj;
  console.log(form.value)
  dialogFormVisibleAdd.value = true;
}
const changeCourse2 = () => {
  if (form.value.consultant.realname != null && form.value.coursetype.name != null) {
    let file1 = document.getElementById("tx1")
    let file2 = document.getElementById("tx2")
    if (file1.files.length > 0) {
      if (file2.files.length > 0) {
        const formData1 = new FormData();
        const formData2 = new FormData();
        formData2.append("file", file2.files[0]);
        formData1.append("file", file1.files[0]);
        axios.post("/file", formData1, {
          headers: {"Content-Type": "multipart-form-data"}
        })
            .then(res => {
              form.value.videoUrl = res.data
              console.log(res.data)
              axios.post("/file", formData2, {headers: {"Content-Type": "multipart-form-data"}})
                  .then(res => {
                    form.value.imageUrl = res.data
                    console.log(res.data)
                    update()
                  })
                  .catch(err => console.log(err))
            })
            .catch(err => console.log(err))

      } else {
        const formData1 = new FormData();
        formData1.append("file", file1.files[0]);
        axios.post("/file", formData1, {headers: {"Content-Type": "multipart-form-data"}})
            .then(res => {
              form.value.videoUrl = res.data
              update()
            })
            .catch(err => console.log(err))
      }
    } else {
      if (file2.files.length > 0) {
        const formData2 = new FormData();
        formData2.append("file", file2.files[0]);
        axios.post("file", formData2, {headers: {"Content-Type": "multipart-form-data"}})
            .then(res => {
              form.value.imageUrl = res.data
              update()
              console.log(res.data)
            })
            .catch(err => console.log(err))
      } else {
        update()
      }
    }


    dialogFormVisibleAdd.value = false;
  } else {
    ElMessage({
      message: '请选择该课程的咨询师以及课程的类型',
      type: 'error',
      plain: true,
    })
  }
}

//删除课程
const deleteCourse1 = (courseId) => {

  num.value = courseId
  str3.value = "确定删除该条数据吗?"
  dialogFormVisibleDel.value = true;
}
const deleteCourse2 = () => {

  axios.delete("/course", {
    params: {courseId: num.value}
  })
      .then(res => {
        findAll()
        console.log(res.data)
      })
      .catch(err => console.log(err))
  dialogFormVisibleDel.value = false;
}

// 批量删除购买记录
const deleteSelect1 = () => {

  str3.value = "确定删除选中的所有数据吗?"
  dialogFormVisibleDel.value = true;
}
const deleteSelect2 = () => {
  axios.delete("/course/select", {
    data: numArr.value
  })
      .then(res => {
        findAll()
        console.log(res.data)
      })
      .catch(err => console.log(err))
  dialogFormVisibleDel.value = false;
}

//模糊查询
const search = () => {
  findAll()
}

//重置搜索
const resetSearch = () => {

  courseName.value = null
  consultantName.value = null
  courseType.value = null
  findAll()
}

//查询所有购买记录
const findAll = () => {

  axios.get("/course", {
    params: {
      courseName: courseName.value,
      consultantName: consultantName.value,
      courseType: courseType.value,
      pageNum: pageNum.value,
      pageSize: pageSize.value
    }
  })
      .then(res => {
        tableData.value = res.data.data.list
        console.log(res.data.data)
        total.value = res.data.data.total
        for (const course of tableData.value) {
          // console.log(course)
          imageArr.value[course.courseId] = course.imageUrl
          videoArr.value[course.courseId] = course.videoUrl
        }
      })
      .catch(err => {
        console.log(err)
      })
}

// 查找所有的课程二级类型
const findType = () => {
  axios.get("/coursetype")
      .then(res => {
        console.log(res.data)
        typeArr.value = res.data.data;
      })
      .catch(err => {
        console.log(err)
      })
}

//查找所有的咨询师数组
const findConsultant = () => {
  axios.get("/consultant/findAllConsultant", {params: {pageNum: 1, pageSize: 100}})
      .then(res => {

        consultantArr.value = res.data.data.list

        console.log(consultantArr.value)
      })
      .catch(err => console.log(err))
}

// 动态展示选择表中的数据行
const liveshow = (selection) => {
  numArr.value = []
  for (const s of selection) {
    numArr.value.push(s.courseId)
  }
  console.log(numArr.value)
}

onMounted(() => {
  findAll()
  findType()
  findConsultant()
})
</script>

<template>


  <div class="top">
    课程名称
    <el-input v-model="courseName" style="width: 240px" placeholder="请输入课程名称"/>
    咨询师名称
    <el-select v-model="consultantName" placeholder="请选择咨询师" style="width: 240px">
      <el-option v-for="(value,index) in consultantArr" :key="index" :label="value.realname" :value="value.realname"/>
    </el-select>
    <!--    咨询师名称 <el-input v-model="consultantName" style="width: 240px" placeholder="请输入咨询师名称" />-->
    课程类型
    <el-select v-model="courseType" placeholder="选择类型" style="width: 240px">
      <el-option v-for="(value,index) in typeArr" :key="index" :label="value.name" :value="value.name"/>
    </el-select>


    <el-button type="primary" style="margin-left: 20px" @click="search" :icon="Search">搜索</el-button>

    <el-button type="warning" style="margin-left: 20px" @click="resetSearch" :icon="Refresh">重置</el-button>
  </div>


  <div class="table">

    <div class="tar">
      <el-button type="primary" plain @click="addCourse1">添加</el-button>
      <el-button type="danger" plain @click="deleteSelect1">批量删除</el-button>
    </div>

    <el-table :data="tableData" @selection-change="liveshow" style="width: 1200px">
      <el-table-column type="selection" width="55"/>
      <el-table-column property="courseId" label="课程编号" width="120"/>
      <el-table-column property="title" label="课程名称" width="120"/>
      <el-table-column property="videoUrl" label="课程视频" width="170">
        <template #default="scope">
          <video controls :src="videoArr[scope.row.courseId]" width="150px" height="150px"></video>
        </template>
      </el-table-column>
      <el-table-column property="description" label="课程简介" width="120"/>
      <el-table-column property="targetAudience" label="适用人群" width="120"/>
      <el-table-column property="learningOutcomes" label="学习收获" width="120"/>
      <el-table-column property="subscriptionNotice" label="订阅须知" width="120"/>
      <el-table-column property="originalPrice" label="原始价格" width="120"/>
      <el-table-column property="discount" label="折扣" width="120"/>
      <el-table-column property="imageUrl" label="课程图片" width="120">
        <template #default="scope">
          <img :src="imageArr[scope.row.courseId]" alt="" width="100px" height="100px">
        </template>
      </el-table-column>
      <el-table-column property="consultant.realname" label="咨询师" width="120"/>
      <el-table-column property="validityPeriod" label="有效期" width="120"/>
      <el-table-column property="studyTimes" label="学习次数" width="120"/>
      <el-table-column property="coursetype.name" label="课程类型" width="120"/>
      <el-table-column property="subjectTimes" label="总时长" width="120"/>
      <el-table-column property="lessonNum" label="课件数量" width="120"/>
      <el-table-column property="reviewNum" label="评价数量" width="120"/>
      <el-table-column property="likeNum" label="收藏数量" width="120"/>
      <el-table-column property="buyNum" label="购买数量" width="120"/>
      <el-table-column property="" label="操作" width="180">
        <template #default="scope">
          <el-button type="warning" round @click="changeCourse1(scope.row)">修改</el-button>
          <el-button type="danger" round @click="deleteCourse1(scope.row.courseId)">删除</el-button>
        </template>

      </el-table-column>
    </el-table>
    <div class="example-pagination-block">
      <el-pagination layout="prev, pager, next" :total="total" :page-size="pageSize" @currentChange="change"
                     @nextClick="nextPage" @prevClick="prevPage"/>
    </div>

    <!--    添加课程-->
    <el-dialog v-model="dialogFormVisibleAdd" :title="str1" width="500">
      <el-form :model="form">
        <el-form-item label="课程名称" :label-width="formLabelWidth">
          <el-input v-model="form.title" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="课程视频" :label-width="formLabelWidth">
          <input type="file" id="tx1">
        </el-form-item>
        <el-form-item label="课程简介" :label-width="formLabelWidth">
          <el-input v-model="form.description" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="适用人群" :label-width="formLabelWidth">
          <el-input v-model="form.targetAudience" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="学习收获" :label-width="formLabelWidth">
          <el-input v-model="form.learningOutcomes" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="订阅须知" :label-width="formLabelWidth">
          <el-input v-model="form.subscriptionNotice" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="原始价格" :label-width="formLabelWidth">
          <el-input v-model="form.originalPrice" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="折扣" :label-width="formLabelWidth">
          <el-input v-model="form.discount" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="课程图片" :label-width="formLabelWidth">
          <input type="file" id="tx2">
        </el-form-item>
        <el-form-item label="咨询师名称" :label-width="formLabelWidth">
          <el-select v-model="form.consultant.realname" placeholder="请选择咨询师" style="width: 240px">
            <el-option v-for="(value,index) in consultantArr" :key="index" :label="value.realname"
                       :value="value.realname"/>
          </el-select>
        </el-form-item>
        <el-form-item label="有效期" :label-width="formLabelWidth">
          <el-input v-model="form.validityPeriod" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="学习次数" :label-width="formLabelWidth">
          <el-input v-model="form.studyTimes" autocomplete="off"/>
        </el-form-item>
        <!--      课程类型下拉框-->

        <el-form-item label="课程类型" :label-width="formLabelWidth">
          <el-select v-model="form.coursetype.name" placeholder="请选择课程类型">
            <el-option v-for="(value,index) in typeArr" :key="index" :label="value.name" :value="value.name"/>
          </el-select>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisibleAdd= false">取消</el-button>
          <el-button type="primary" @click="(str1===str2)?addCourse2():changeCourse2()">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog v-model="dialogFormVisibleDel" title="删除信息" width="500" draggable>
      <span>{{ str3 }}</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisibleDel = false">取消</el-button>
          <el-button type="primary" @click="(str3===str4)?deleteCourse2():deleteSelect2()">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>


  </div>

</template>

<style scoped>
.top {
  padding: 20px 0;
  margin: 0 20px;
}

.table {
  padding: 20px 0;
  margin: 0 20px;
}

.tar {
  margin-bottom: 30px;
}

.example-pagination-block {
  margin-top: 10px;
}

</style>